package socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/*
服务端的练习和完善，
 */
public class ServerPlus5 {

    private  List<PrintWriter> allOut = new ArrayList<>();
    private ServerSocket serverSocket;

    public ServerPlus5(){
        try {
            serverSocket = new ServerSocket(8088);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start(){
        try{
            while (true) {
                System.out.println("等待连接");
                Socket socket = serverSocket.accept();
                System.out.println("连接成功");
                Runnable r = new ClientHandler(socket);
                Thread t = new Thread(r);
                t.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        ServerPlus5 sp = new ServerPlus5();
        sp.start();

    }

    private  class ClientHandler implements Runnable{
        private Socket socket;
        private String name;

        public ClientHandler(Socket socket){
            this.socket=socket;
            this.name=socket.getInetAddress().getHostName();
        }
        @Override
        public void run() {
            //提高pw的作用域，以便在finally中可以将其从allOut集合中删除
            PrintWriter pw  = null;
            try {
                //读
                InputStream is= socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);
                //原数据返回
                OutputStream os = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(os,StandardCharsets.UTF_8);
                BufferedWriter bw = new BufferedWriter(osw);
               pw = new PrintWriter(bw,true);
               //多线程都指向同一个集合添加元素 ，会出现并发安全问题，因此必须同步执行
                synchronized (allOut) {//通常同步监视器对象就选取临界资源
                    allOut.add(pw);
                }
                sendMessage(name + "已经上线了。当前在线人数:" + allOut.size() + "人！");

                String temp;
                while ((temp = br.readLine())!=null){
                    if ("exit".equals(temp)){

                        break;
                    }
                   sendMessage(name+":" +temp);
                }
                br.close();
                pw.close();
            } catch (IOException e) {
               // e.printStackTrace();
                //在finlly中处理客户端断开后的操作
            }finally {
                synchronized (allOut) {
                    allOut.remove(pw);
                }
                sendMessage(name + "已经下线了。当前在线人数:" + allOut.size());
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        private void sendMessage(String temp){
            System.out.println(temp);
            synchronized (allOut) {
                //增强for遍历底层是迭代器 遍历过程中 不能进行集合增删
                //加锁 同步处理进行互斥
                for (PrintWriter o : allOut){
                    o.println(temp);
                }
            }
        }

    }

}
